<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>聊天室客户端</title>
    <script src="https://cdn.bootcss.com/socket.io/2.0.4/socket.io.js"></script>
    <style type="text/css">
        *{ margin: 0; padding:0;}
        .inputWrap {
            position: absolute;
            width: 100vw;
            height: 100vh;
            text-align: center;
            top: 54%;
            position: relative;
            background: rgba(1, 1, 1, .2);
        }

        .inputItem {
            top: 31%;
            position: relative;
        }

        .title{
            display: flex;
            justify-content: space-between;
            background-color: rgba(0,0,0,.7);
            color: #fff;
            padding: 13px;
        }
        .online{
            margin: 10px 5px;
            background-color: rgba(0,0,0,.1);
            font-size: 9px;
            line-height: 20px;
            text-indent: 9px;
        }

        .bottom{
            display: flex;
            position: fixed;
            bottom: 10px;
            margin-left: 20px;
        }
        .bottom .inputContent {
            width: 250px;
            box-shadow: 3px 3px 0px #CCC;
        }
        .bottom .submit{
            flex:1;
            background-color: #ccc;
            width: 100px;
            box-shadow: 3px 3px 0px #999;
            margin-left: 17px;
        }

        .leftCon{
            text-align: left;
            padding-left: 10px;
            height: 40px;
        }
        .rightCon{
            text-align: right;
            padding-right: 10px;
            height: 40px;
        }
        .dialog{
            padding: 5px;
            box-shadow: 3px 3px 3px #ccc;
        }
        .name{
            display: inline-block;
            width:65px;
        }
        .leftCon .name::after{
            content: ':'
        }
        .rightCon .name::before{
            content: ':'
        }
    </style>
</head>

<body>
    <!-- 登录界面 -->
    <div id="loginbox" class="inputWrap">
        <div class="inputItem">
            请先输入你在聊天室的昵称
            <br />
            <br />
            <input type="text" placeholder="请输入用户名" id="username" name="username">
            <input type="button" value="提交" id="username" onclick="CHAT.usernameSubmit();">
        </div>
    </div>

    <!-- 聊天界面 -->
    <div id="chatbox" style="display: none;">
            <div class="title">
                <span>多人聊天室</span>
                <span>
                    <span id="showusername"></span>
                    |
                    <span onclick="CHAT.logout();" style="cursor: pointer;">退出</span>
                </span>
            </div>

            <div class="online"> 
                <span id="onlinecount"></span>
            </div>

            <div id="message" class="chatContent">
                <!-- <div class="leftCon">
                    <span class="name">汤姆：</span>
                    <span class="dialog">大家好，我是汤姆</span>
                </div>
                <div class="rightCon">
                    <span class="dialog">欢迎汤姆</span>
                    <span class='name'>: 杰克</span>
                </div> -->
            </div>

            <div class="bottom">    
                <input id="content" class="inputContent" type="text" placeholder="请输入聊天内容，并按Enter键">
                <input class="submit" type="submit" onclick="CHAT.submit();" value="提交">
            </div>
    </div>

    <script type="text/javascript">
        (function () {
            var d = document,
                w = window,
                p = parseInt,
                dd = d.documentElement,
                db = d.body,
                dc = d.compatMode == 'CSS1Compat',
                dx = dc ? dd : db,
                ec = encodeURIComponent;

            w.CHAT = {
                msgObj:d.getElementById("message"),
                username: null,
                userid: null,
                socket: null,
                //第一个界面用户提交用户名
                usernameSubmit: function () {
                    var username = d.getElementById("username").value;
                    if (username != "") {
                        d.getElementById("username").value = '';
                        d.getElementById("loginbox").style.display = 'none';
                        d.getElementById("chatbox").style.display = 'block';
                        console.log(username);
                        this.init(username);
                    }
                    return false;
                },
                submit: function(){
                    var content = d.getElementById('content').value;
                    if(content != ''){
                        var obj = {
                            userid: this.userid,
                            username: this.username,
                            content: content
                        };
                        this.socket.emit('message',obj);
                        d.getElementById('content').value = '';
                    }
                    return false;
                },
                // 退出登录
                logout: function(){
                    location.reload();
                },
                // 根据时间戳随机的生成一个用户id
                genUid:function(){
                    return new Date().getTime()+""+Math.floor(Math.random()*899+100);
                },
                // 更新系统消息，在用户加入，退出时调用
                updateSysMsg: function(o, action){
                    var onlineUsers = o.onlineUsers;
                    var onlineCount = o.onlineCount;
                    var user = o.user;

                    // 更新在线人数
                    var userhtml = '';
                    var separator = '';

                    for(key in onlineUsers){
                        if(onlineUsers.hasOwnProperty(key)){
                            userhtml += separator + onlineUsers[key];
                            separator = ',';
                        }
                    }
                    d.getElementById("onlinecount").innerHTML = '当前共有 '+onlineCount+' 人在线，在线列表：'+userhtml;
                    
                    var html = '';
                    html += '<span>系统消息:</span>';
                    html += '<span class="dialog">';
                    html += user.username;
                    html += (action == 'login') ? ' 加入了聊天室' : ' 退出了聊天室';
                    html += '</span>';
                    var div = d.createElement('div');
                    div.className = 'leftCon';
                    div.innerHTML = html;
                    this.msgObj.appendChild(div);

                },
                // 初始化
                init: function(username){
                    this.userid = this.genUid();
                    this.username = username;

                    d.getElementById('showusername').innerHTML = this.username;

                    // 连接websocket服务
                    this.socket = io.connect('ws://localhost:3000/');
                    this.socket.emit('login', { userid: this.userid, username: this.username });

                    //监听新用户登录
                    this.socket.on('login', function(o){
                        CHAT.updateSysMsg(o, 'login');
                    });

                    //监听用户退出
                    this.socket.on('logout', function(o){
                        CHAT.updateSysMsg(o, 'logout');
                    });

                    //监听消息发送
                    this.socket.on('message', function(obj){
                        var isme = (obj.userid == CHAT.userid) ? true : false;
                        var contentDiv = '<span class="dialog">'+obj.content+'</span>';
                        var usernameDiv = '<span class="name">'+obj.username+'</span>';
        
                        var div = d.createElement('div');
                        if(isme){
                            div.className = 'rightCon';
                            div.innerHTML = contentDiv + usernameDiv;
                        } else {
                            div.className = 'leftCon';
                            div.innerHTML = usernameDiv + contentDiv;
                        }
                        CHAT.msgObj.appendChild(div);
                    });
                }
            }
        })();
    </script>
</body>

</html>